const httpCodes = require("./http-codes");
const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
const collection = db.collection("news-articles-image");
const limit = 10;

/**
 * 根据活动的种类id获取文章列表
 * 并且获取文章对应的优惠券信息
 * @param {*} category_id 活动种类id
 * @param {*} length 当前文章的数量作为偏移量
 */
async function getArticlesAndCouponInfo(category_id, length = 0) {
  const res = await collection
    .aggregate()
    .match({ category_id, article_status: 1 })
    .lookup({
      from: "coupons",
      let: {
        images_coupon_id: "$coupon_id",
      },
      pipeline: $.pipeline()
        .match(
          dbCmd.expr(
            $.and([$.eq(["$_id", "$$images_coupon_id"]), $.neq(["$status", 2])])
          )
        )
        .project({
          _id: 1,
          name: 1,
          discount: 1,
          validity: 1,
          status: 1,
          customImage: 1,
        })
        .skip(length)
        .limit(limit)
        .done(),
      as: "coupon_info",
    })
    .sort({
      last_modify_date: -1,
    })
    .end();

  return res;
}

// 添加统一的错误处理函数
function handleError(error, operation) {
  console.error(`${operation}失败:`, error);
  return {
    code: httpCodes.INTERNAL_SERVER_ERROR,
    data: null,
    message: `${operation}失败: ${error.message || "未知错误"}`, // 增加错误详情
  };
}

// 提取通用的分页逻辑
async function fetchArticlesWithPagination(category_id, length = 0) {
  try {
    const res = await getArticlesAndCouponInfo(category_id, length);
    const countResult = res.data.affectedDocs || 0; // 确保 countResult 不为空
    const hasMore = countResult >= limit; // 是否还有更多数据

    return {
      code: httpCodes.SUCCESS,
      data: {
        data: [...res?.data],
        count: countResult,
        hasMore, // 添加标志位
      },
      message: "获取文章成功",
    };
  } catch (error) {
    return handleError(error, "获取文章");
  }
}

module.exports = {
  async getArticles(category_id) {
    return fetchArticlesWithPagination(category_id);
  },

  async loadMore(category_id, length) {
    return fetchArticlesWithPagination(category_id, length);
  },
};
